// pages/detail/detail.js
import config from "../../utils/config";

const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';

const find = _.find;


function isNumericStart(str) {
    return /^\d/.test(str);
}

function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}

let EBOriginData = '';
let upgradeIndex = 1;
let per_package_size = 128
Page({

    /**
     * 页面的初始数据
     */
    data: {
        active: 1,
        deviceId: '',
        name: '',
        type: '',
        connected: false,
        loading: false,
        serviceIds: [],
        serviceIdsCharIdsMap: [],
        selectServerChars: {},
        logs: [],
        all_concentrator_firmwares: [],
        latitude: '',
        longitude: '',
        editlatitude: 42.92736760935551,
        editlongitude: 89.19229343394916,
        markers: [],
        editmarkers: [],
        postIndex: 0,
        eventIndex: 0,
        postIndex2: 0,
        postArray: ['01', '02', '03', '04', '05', '06', '07', '08'],
        postArray2: ['01', '02', '03', '04', '05', '06', '07', '08'],
        eventArray: ['充值记录', '阀控记录', '设底度记录', '清零记录', '端子变更记录', '掉电记录'],
        checkItems: [{
            value: 'USA',
            name: '取系统时间'
        },

        ],
        update_type:'',
        uploading:false,
        valveIndex: 0,
        latest_concentrator_firmwares:{},
        valveArray: [{
            name: '开阀',
            key: '55'
        }, {
            name: '关阀',
            key: 'AA'
        }],
        checkValveItems: [{
            value: 'D0',
            name: '开启预付量功能'
        },
            {
                value: 'D1',
                name: '5天不计量传感器重新上电'
            },
            {
                value: 'D2',
                name: '开启阀门维护'
            },
            {
                value: 'D3',
                name: '开启泄露关阀'
            },
            {
                value: 'D4',
                name: '开启磁干扰关阀'
            },
            {
                value: 'D5',
                name: '开启点冻结上报'
            },
            {
                value: 'D6',
                name: '开启掉电关阀'
            },

        ],
        E4data: {},
        timeArr: [
            [],
            [],
            []
        ],
        dateIndex: util.formatDate(new Date()),
        timeIndex: [0, 0, 0],
        input0:'',
        input1: '',
        input2: '',
        input3: '',
        input4: '',
        E5data: {},
        E7data: {},
        EAdata: {},
        EBdata: {},
        EFdata: {},
        F0data: {},
        portsArr: [],
        E6data: {},
        selectFirmware: {},
        selectLocalFirmware: {}
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const that = this
        let timeArr = this.data.timeArr
        for (let i = 0; i < 24; i++) {
            timeArr[0][i] = util.fixedZero(i)
        }
        for (let i = 0; i < 60; i++) {
            timeArr[1][i] = util.fixedZero(i)
            timeArr[2][i] = util.fixedZero(i)
        }
        this.setData({
            timeArr: timeArr
        })
        console.log(options);
        this.setData({
            deviceId: options.deviceId ,
            name: options.name ,
            type: options.type,
            connected: options.connected === '1',
        }, function () {
            this.getBLEDeviceServices(this.data.deviceId)
            if (options.type === '设置上报参数') {
                this.setData({
                    input1: 20,
                    input2: 300
                })
            }
            if(options.type === '位置信息'){

                // this.mapCtx = wx.createMapContext('myMap')

                // this.getLocation()
                wx.request({
                    url: `${config.prefix}/concentrators`,
                    header: {
                        Authorization: `Bearer ${app.globalData.userInfo.token}`
                    },
                    method: 'GET',
                    data: {
                        number: that.data.name
                    },

                    success: function (res) {
                        console.log('get res', res)
                        if (res.statusCode === 200) {
                            if( res.data.data.length===1){
                                let data={
                                    ...res.data.data[0],
                                }

                                that.setData({
                                    id: data.id,
                                    address:data.address,
                                    latitude:data.latitude,
                                    longitude:data.longitude,
                                    markers: [{
                                        id: 1,
                                        latitude: data.latitude,
                                        longitude: data.longitude,
                                        width: '30', // 标记点图标宽度
                                        height: '60' // 标记点图标高度
                                    }],
                                })

                            }


                        }
                    }
                })
            }
            if (options.type === '清零' || options.type === '读事件记录') {
                this.data.postArray.push('FF')
                this.setData({
                    postArray: this.data.postArray

                })
            }
            if (options.type === '固件升级') {
                wx.request({
                    url: `${config.prefix}/ota/all_concentrator_firmwares`,

                    method: 'GET',
                    data: {
                        per_package_size: per_package_size
                    },

                    success: function (res) {
                        console.log('get res', res)
                        if (res.statusCode === 200) {
                            that.setData({
                                all_concentrator_firmwares: res.data.data
                            })
                        } else {
                            console.log('获取所有集中器固件失败')
                        }
                    }
                })
            }
        })
        wx.setNavigationBarTitle({
            title: options.type,
        })
        wx.onBLEConnectionStateChange(function (res) {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            that.writeLogs(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            that.setData({
                connected: res.connected
            }, function () {
                if (res.connected) {
                    this.getBLEDeviceServices(this.data.deviceId)
                } else {
                    that.writeLogs('断开连接')
                }
            })
        })



    },
    getLocation:function(){
        const that=this;
        this.editmapCtx2 = wx.createMapContext('myMap2')
        console.log('getLocation')
        wx.chooseLocation({
            success: res => {
                console.log(res)
                this.setData({
                    editaddress: res.name,
                    editlatitude:res.latitude,
                    editlongitude:res.longitude,
                    editmarkers: [{
                        id: 1,
                        latitude:res.latitude,
                        longitude:res.longitude,
                        width: '30', // 标记点图标宽度
                        height: '60' // 标记点图标高度
                    }],
                })
                // if(that.editmapCtx2){
                //     that.editmapCtx2.moveToLocation()
                // }
            },
            fail: err => {
                console.log(err)
            }
        })
        /*wx.getLocation({
            type: 'wgs84',
            success (res) {
                console.log(res)
              const latitude = res.latitude
              const longitude = res.longitude
              const speed = res.speed
              const accuracy = res.accuracy
              that.setData({
                editlatitude:latitude,
                editlongitude:longitude,
                editmarkers: [{
                    id:accuracy,
                    longitude: longitude,
                    latitude: latitude,
                    width: '30', // 标记点图标宽度
					height: '50' // 标记点图标高度
                  }]
              })
              if(that.editmapCtx2){
                that.editmapCtx2.moveToLocation()
              }
            //   that.editmapCtx2.moveToLocation()

            }
           })*/
    },
    uploadLocation: function (e) {
        console.log('longitude',this.data.editlongitude)
        console.log('latitude',this.data.editlatitude)
        console.log('editaddress',this.data.editaddress)
        const that=this
        wx.request({
            url: `${config.prefix}/concentrators/${this.data.id}`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'PUT',
            data: {
                longitude: this.data.editlongitude,
                latitude: this.data.editlatitude,
                address: this.data.editaddress,
            },

            success: function (res) {
                console.log('get res', res)
                if (res.statusCode === 200) {
                    util.toastError('上传位置成功')
                    that.setData({
                        active:1,
                        address: that.data.editaddress,
                        longitude:that.data.editlongitude,
                        latitude:that.data.editlatitude,
                        markers: [{
                            id:1,
                            longitude: that.data.editlongitude,
                            latitude: that.data.editlatitude,
                            width: '30', // 标记点图标宽度
                            height: '50' // 标记点图标高度
                        }]
                    })


                }
            }
        })

    },
    bindmarkertap: function() {
        wx.openLocation({
            latitude: Number(this.data.latitude), // 纬度，范围为-90~90，负数表示南纬
            longitude: Number(this.data.longitude), // 经度，范围为-180~180，负数表示西经
            scale: 14, // 缩放比例
        })
    },
    changeInput: function (e) {
        const that = this
        console.log('changeValue', e.currentTarget.dataset.item)
        console.log('e.detail.value', e.detail.value)
        this.setData({
            [e.currentTarget.dataset.item]: e.detail.value
        })
    },
    bindTimeChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            timeIndex: e.detail.value
        })
    },
    bindChangeDate: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            dateIndex: e.detail.value
        })
    },
    checkboxChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        const items = this.data.checkItems
        const values = e.detail.value
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            items[i].checked = false

            for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
                if (items[i].value === values[j]) {
                    items[i].checked = true
                    break
                }
            }
        }

        this.setData({
            checkItems: items
        })

    },
    valveCheckboxChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        const items = this.data.checkValveItems
        const values = e.detail.value
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            items[i].checked = false

            for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
                if (items[i].value === values[j]) {
                    items[i].checked = true
                    break
                }
            }
        }

        this.setData({
            checkValveItems: items
        })

    },
    clean: function (e) {

        this.setData({
            logs: []
        })
    },
    bindPickerChangePost: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            postIndex: e.detail.value
        })
    },
    bindPickerChangePostEvent: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            eventIndex: Number(e.detail.value),
            F0data: {}
        })
    },
    bindPickerChangePost2: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            postIndex2: e.detail.value
        })
    },
    bindPickerChangeValve: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            valveIndex: e.detail.value
        })
    },
    getName: function () {
        let n1 = this.data.name.substr(0, 2)
        let n2 = this.data.name.substr(2, 2)
        let n3 = this.data.name.substr(4, 2)
        let n4 = this.data.name.substr(6, 2)
        return `${n4} ${n3} ${n2} ${n1}`
    },
    getTime: function () {
        let date = util.formatTime(new Date())
        let b1 = date.substr(0, 2)
        let b2 = date.substr(2, 2)
        let b3 = date.substr(5, 2)
        let b4 = date.substr(8, 2)
        let b5 = date.substr(11, 2)
        let b6 = date.substr(14, 2)
        let b7 = date.substr(17, 2)
        return `${b7} ${b6} ${b5} ${b4} ${b3} ${b2} ${b1}`
    },
    handleSend82: function () {
        let valve = this.data.valveArray[this.data.valveIndex].key;
        let str = `0E ${this.getName()} 00 82 ${this.data.postArray[this.data.postIndex]} ${valve} 00 ${this.getTime()} ${this.getTime()} 00 00 00 00`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend83: function () {
        let input2 = util.padWithZeros(this.data.input2.toString(16), 4, '0')
        console.log('input2', input2)

        let str = `0E ${this.getName()} 00 83 ${input2.substr(2, 2)} ${input2.substr(0, 2)} ${this.data.timeArr[2][this.data.timeIndex[2]]} ${this.data.timeArr[1][this.data.timeIndex[1]]} ${this.data.timeArr[0][this.data.timeIndex[0]]} 14 00 00`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE2: function () {
        console.log(this.data.checkItems)
        console.log(this.data.dateIndex)
        let str = ''
        if (this.data.checkItems[0].checked) {
            str = `0E ${this.getName()} 00 E2 ${this.getTime()}`

        } else {
            str = `0E ${this.getName()} 00 E2 ${this.data.timeArr[2][this.data.timeIndex[2]]} ${this.data.timeArr[1][this.data.timeIndex[1]]} ${this.data.timeArr[0][this.data.timeIndex[0]]} ${this.data.dateIndex.substr(8, 2)} ${this.data.dateIndex.substr(5, 2)} ${this.data.dateIndex.substr(2, 2)} ${this.data.dateIndex.substr(0, 2)}`

        }

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE8: function () {
        let input1 = util.padWithZeros(this.data.input1.toString(16), 2, '0')
        console.log('input1', input1)
        console.log(this.data.dateIndex)
        let str = `0E ${this.getName()} 00 E8 ${this.data.postArray[this.data.postIndex]} ${this.data.timeArr[1][this.data.timeIndex[1]]} ${this.data.timeArr[0][this.data.timeIndex[0]]} ${this.data.dateIndex.substr(8, 2)} ${this.data.dateIndex.substr(5, 2)} ${this.data.dateIndex.substr(2, 2)} ${this.data.dateIndex.substr(0, 2)} ${input1}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE9: function () {
        let input1 = util.padWithZeros(this.data.input1.toString(16), 2, '0')
        console.log('input1', input1)
        console.log(this.data.dateIndex)
        let str = `0E ${this.getName()} 00 E9 ${this.data.postArray[this.data.postIndex]} ${this.data.dateIndex.substr(8, 2)} ${this.data.dateIndex.substr(5, 2)} ${this.data.dateIndex.substr(2, 2)} ${this.data.dateIndex.substr(0, 2)} ${input1}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)

        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE3: function () {
        let str = `0E ${this.getName()} 00 E3 ${this.data.postArray[this.data.postIndex]} ${this.data.postArray2[this.data.postIndex2]}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend84: function () {
        if (!this.data.input1 || !this.data.input2) {
            util.toastError('IP和端口不能为空')
            return
        }
        if (!util.isValidIPv4(this.data.input1)) {
            util.toastError('IP地址格式错误')
            this.writeLogs(`IP地址格式错误`, 'red');
            return
        }

        let i1 = Number(this.data.input1.split(".")[0]).toString(16)
        let i2 = Number(this.data.input1.split(".")[1]).toString(16)
        let i3 = Number(this.data.input1.split(".")[2]).toString(16)
        let i4 = Number(this.data.input1.split(".")[3]).toString(16)

        let input2 = util.padWithZeros(Number(this.data.input2).toString(16), 4);
        console.log('input2', input2)

        let str = `0E ${this.getName()} 00 84 ${util.fixedZero(i4)} ${util.fixedZero(i3)} ${util.fixedZero(i2)} ${util.fixedZero(i1)} ${input2.substr(0, 2)} ${input2.substr(2, 2)}`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend85: function () {
        //input0为表底数
        //input1为表盘数
        let input0 = util.padWithZeros(parseInt(Number(this.data.input0) * 1000), 8, '0')
        let input1 = util.padWithZeros(parseInt(Number(this.data.input1) * 1000), 8, '0')
        console.log('input1', input1)
        let str = `0E ${this.getName()} 00 85 ${this.data.postArray[this.data.postIndex]} ${input0.substr(6, 2)} ${input0.substr(4, 2)} ${input0.substr(2, 2)} ${input0.substr(0, 2)} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} 2C`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend86: function () {
        return
        if (!this.data.input1 && !this.data.input2) {
            util.toastError('所有值不能为空')
            return false
        }
        let input1 = util.padWithZeros(parseInt(Number(this.data.input1) * 1000).toString(16), 8, '0')
        let input2 = util.padWithZeros(Number(this.data.input2).toString(16), 4, '0')
        console.log('input1', input1)
        let str = `0E ${this.getName()} 00 86 ${this.data.postArray[this.data.postIndex]} ${input1.substr(6, 2)} ${input1.substr(4, 2)} ${input1.substr(2, 2)} ${input1.substr(0, 2)} ${input2.substr(2, 2)} ${input2.substr(0, 2)} 00 00`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend87: function () {
        console.log('this.data.input3', this.data.input3)
        if (!this.data.input1 && !this.data.input2 && !this.data.input3 && !this.data.input4) {
            util.toastError('所有值不能为空')
            return false
        }
        console.log(this.data.checkValveItems)

        let conf = '0';
        if (this.data.checkValveItems[6].checked) {
            conf += '1'
        } else {
            conf += '0'
        }

        if (this.data.checkValveItems[5].checked) {
            conf += '1'
        } else {
            conf += '0'
        }

        if (this.data.checkValveItems[4].checked) {
            conf += '1'
        } else {
            conf += '0'
        }

        if (this.data.checkValveItems[3].checked) {
            conf += '1'
        } else {
            conf += '0'
        }


        if (this.data.checkValveItems[2].checked) {
            conf += '1'
        } else {
            conf += '0'
        }

        if (this.data.checkValveItems[1].checked) {
            conf += '1'
        } else {
            conf += '0'
        }
        if (this.data.checkValveItems[0].checked) {
            conf += '1'
        } else {
            conf += '0'
        }

        console.log('conf', conf)
        console.log('binaryToHexString conf', util.binaryToHexString(conf))

        let input1 = util.padWithZeros(Number(this.data.input1).toString(16), 4, '0')
        let input2 = util.padWithZeros(Number(this.data.input2).toString(16), 4, '0')
        let input3 = util.padWithZeros(this.data.input3, 2, '0')
        let input4 = util.padWithZeros(this.data.input4, 2, '0')
        console.log('input1', input1)
        console.log('input2', input2)
        let str = `0E ${this.getName()} 00 87 ${this.data.postArray[this.data.postIndex]} ${util.padWithZeros(util.binaryToHexString(conf), 2)} 00 00 00 ${input1.substr(2, 2)} ${input1.substr(0, 2)} ${input2.substr(2, 2)} ${input2.substr(0, 2)} ${input3} ${input4} 00 00 00 00 00 00 00 00`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE6: function () {
        let str = `0E ${this.getName()} 00 E6 ${this.data.postArray[this.data.postIndex]}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendF0: function () {
        let str = `0E ${this.getName()} 00 F0 ${this.data.postArray[this.data.postIndex]} ${util.padWithZeros(Number(this.data.eventIndex) + 1, 2, '0')} ${util.padWithZeros(Number(this.data.input1).toString(16), 2, '0')}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendEE: function () {
        let str = `0E ${this.getName()} 00 EE`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendEF: function () {
        let str = `0E ${this.getName()} 00 EF`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE1: function () {
        if (this.data.input1.length !== 8) {
            util.toastError('采集器号长度不正确')
            return
        }

        let str = `0E ${this.getName()} 00 E1 ${this.data.input1.substr(6, 2)} ${this.data.input1.substr(4, 2)} ${this.data.input1.substr(2, 2)} ${this.data.input1.substr(0, 2)}`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendEC: function () {

        let str = `0E ${this.getName()} 00 EC`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendED: function () {

        let str = `0E ${this.getName()} 00 ED`

        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE0: function () {

        let str = `0E ${this.getName()} 00 E0`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE4: function () {

        let str = `0E ${this.getName()} 00 E4`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE5: function () {

        let str = `0E ${this.getName()} 00 E5`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendE7: function () {

        let str = `0E ${this.getName()} 00 E7`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendEA: function () {

        let str = `0E ${this.getName()} 00 EA`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSendEB: function () {
        console.log('this.getName()',this.getName())
        let str = `0E ${this.getName()} 00 EB`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    handleSend88: function (e) {
        const that = this;
        console.log('changeValue', e.currentTarget.dataset)
        if(this.data.uploading){
            util.toastError('固件正在升级中...')
            return
        }
        that.setData({
            update_type:e.currentTarget.dataset.update_type
        })
        wx.showModal({
            title: '提示',
            content: `确定要${e.currentTarget.dataset.version?e.currentTarget.dataset.version:'升级'}?升级时请保持页面在前台且亮屏,否则会升级失败`,
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    that.setData({
                        selectFirmware: {
                            ...e.currentTarget.dataset
                        }
                    })
                    let check_code = e.currentTarget.dataset.check_code //新固件效验码
                    let package_count = util.padWithZeros(Number(e.currentTarget.dataset.package_count).toString(16), 4) //新固件总包数
                    let str = `9E ${that.getName()} 00 88 ${util.padWithZeros(check_code, 2)} ${package_count.substr(2, 2)} ${package_count.substr(0, 2)}`
                    // let str = `9E ${this.getName()} 00 88 00 ${package_count.substr(2, 2)} ${package_count.substr(0, 2)}`
                    let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
                    console.log('sendHex', sendHex)
                    that.writeLogs(`下发数据：${sendHex}`, 'orange');
                    that.writeBLECharacteristicValue(sendHex)


                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })


    },
    handleSend89: function (index, current_package_size, content) {
        console.log('系统向采集器发送升级包（系统回复采集器）' + index)
        this.setData({
            uploading:true
        })
        let zgsw = '';
        if (index === this.data.package_count) {
            zgsw = '8E'
        } else if (Number(index) === 1) {
            zgsw = '96'
        } else {
            zgsw = '86'
        }
        // console.log('zgsw',zgsw)
        index = util.padWithZeros(Number(index).toString(16), 4) //当前请求包序号
        current_package_size = util.padWithZeros(Number(current_package_size).toString(16), 4) //当前升级包大小
        let str = `9E ${this.getName()} 00 89 ${index.substr(2, 2)} ${index.substr(0, 2)} ${current_package_size.substr(2, 2)} ${current_package_size.substr(0, 2)} ${util.addSpaceEveryTwoChars(content)}`
        let sendHex = '68 ' + str + ' ' + util.calc(str) + ' 16'
        // console.log('sendHex', sendHex)
        this.writeLogs(`下发数据：${sendHex}`, 'orange');
        this.writeBLECharacteristicValue(sendHex)
    },
    writeBLECharacteristicValue(sendHex) {
        if (!this.data.connected) {
            util.toastError('请先连接设备');
            return false
        }
        if (!this.data.selectServerChars.deviceId) {
            util.toastError('请等待初始化或者重新连接')
            return false
        }
        var typedArray = new Uint8Array(sendHex.match(/[\dA-F]{2}/gi).map(function (h) {
            return parseInt(h, 16)
        }))
        // console.log(typedArray)
        const that = this
        var writeValue = typedArray.buffer
        wx.writeBLECharacteristicValue({
            deviceId: this.data.selectServerChars.deviceId,
            serviceId: this.data.selectServerChars.serviceId,
            characteristicId: this.data.selectServerChars.writeCharUUID,
            value: writeValue,
            success(res) {
                // that.writeLogs("下发数据成功: " + sendHex, 'green');
                // console.log(sendHex.substr(12, 2))
                //68 0E 68 57 89 76 00 89 01 00 00
                // console.log(sendHex)
                if (sendHex.substr(21, 2) === '89'&&Number(that.data.update_type)===1) {
                    // const all_concentrator_firmwares = that.data.all_concentrator_firmwares;
                    let latest_concentrator_firmwares = that.data.latest_concentrator_firmwares;
                    // const idx = inArray(all_concentrator_firmwares, 'id', that.data.selectFirmware.id)
                    // console.log('idx', idx)
                    // console.log('that.data.selectFirmware.id', that.data.selectFirmware.id)
                    // all_concentrator_firmwares[idx] = {
                    //     ...that.data.selectFirmware,
                    //     upgradePer: Math.round(parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`, 16) / that.data.selectFirmware.package_count * 100)
                    // }
                    latest_concentrator_firmwares = {
                        ...that.data.latest_concentrator_firmwares,
                        upgradePer: Math.round(parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`, 16) / that.data.latest_concentrator_firmwares.package_count * 100)
                    }
                    that.setData({
                        latest_concentrator_firmwares
                    })
                    if (parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`, 16) === Number(that.data.latest_concentrator_firmwares.package_count)) {
                        that.setData({
                            uploading:false
                        })
                        util.toastError('升级完成')
                        that.writeLogs(`升级完成`, 'green')
                    }
                    that.writeLogs(`共计${that.data.latest_concentrator_firmwares.package_count}包,第${parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`,16)}包已下发`, 'green');
                    that.writeLogs(`------------------------`, 'green')

                }  else  if (sendHex.substr(21, 2) === '89'&&Number(that.data.update_type)===2) {
                    let selectLocalFirmware=that.data.selectLocalFirmware
                    selectLocalFirmware = {
                        ...that.data.selectLocalFirmware,
                        upgradePer: Math.round(parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`, 16) / selectLocalFirmware.package_count * 100)
                    }
                    that.setData({
                        selectLocalFirmware
                    })
                    if (parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`, 16) === Number(selectLocalFirmware.package_count)) {
                        that.setData({
                            uploading:false
                        })
                        util.toastError('升级完成')
                        that.writeLogs(`升级完成`, 'green')
                    }
                    that.writeLogs(`共计${selectLocalFirmware.package_count}包,第${parseInt(`${sendHex.substr(27, 2)}${sendHex.substr(24, 2)}`,16)}包已下发`, 'green');
                    that.writeLogs(`------------------------`, 'green')

                }else if(sendHex.substr(21, 2) === 'E0'){
                    util.toastError('请求上线下发成功')
                } else {
                    util.toastError('操作下发成功')
                }


            },
            fail: function (res) {
                console.log(res);
                that.writeLogs("下发数据失败: " + res.errCode, 'red');
                util.bleErrCode(res.errCode);
            }
        })
    },
    recvBLECharacterNotice: function (deviceId, serviceId, charId) {
        //接收设置是否成功
        this.writeLogs("注册Notify服务");
        var that = this;
        wx.notifyBLECharacteristicValueChange({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: charId,
            state: true, //启用Notify功能
            success: function (res) {
                wx.onBLECharacteristicValueChange(function (res) {
                    console.log(res);
                    that.writeLogs("收到Notify数据: " + util.addSpaceEveryTwoChars(util.ab2hex(res.value)));
                    let notifyData = util.ab2hex(res.value)
                    console.log('notifyData', notifyData)
                    if (that.data.type === '读电压电流'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        that.setData({
                            E4data: {
                                d1: `${notifyData.substr(18, 2)}${notifyData.substr(16, 2)}`,
                                d2: `${notifyData.substr(22, 2)}${notifyData.substr(20, 2)}`,
                                d3: `${notifyData.substr(26, 2)}${notifyData.substr(24, 2)}`,
                                d4: parseInt(`${notifyData.substr(30, 2)}${notifyData.substr(28, 2)}`, 16),
                            }
                        })
                    }
                    if (that.data.type === '读地址'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        that.setData({
                            E5data: {
                                d1: `${notifyData.substr(10, 2)}${notifyData.substr(8, 2)}${notifyData.substr(6, 2)}${notifyData.substr(4, 2)}`,

                            }
                        })
                    }
                    if (that.data.type === '清零'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        that.setData({
                            E6data: {
                                d1: `${notifyData.substr(16, 2)}`,

                            }
                        })
                    }
                    if (that.data.type === '读上报情况'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        that.setData({
                            E7data: {
                                d1: parseInt(notifyData.substr(22, 2), 16) + ":" + parseInt(notifyData.substr(20, 2), 16) + ":" + parseInt(notifyData.substr(18, 2), 16) + ":" + parseInt(notifyData.substr(16, 2), 16),
                                d2: parseInt(`${notifyData.substr(26, 2)}${notifyData.substr(24, 2)}`, 16),
                                // d3: parseInt(notifyData.substr(42,2), 16)+""+parseInt(notifyData.substr(40,2), 16)+""+parseInt(notifyData.substr(38,2), 16)+""+parseInt(notifyData.substr(36,2), 16)+""+parseInt(notifyData.substr(34,2), 16)+""+parseInt(notifyData.substr(32,2), 16)+''+parseInt(notifyData.substr(30,2), 16)+""+parseInt(notifyData.substr(28,2), 16),
                                d3: parseInt(notifyData.substr(28, 2) + notifyData.substr(30, 2) + notifyData.substr(32, 2) + notifyData.substr(34, 2) + notifyData.substr(36, 2) + notifyData.substr(38, 2) + notifyData.substr(40, 2) + notifyData.substr(42, 2)),
                                d4: notifyData.substr(56, 2) + notifyData.substr(54, 2) + "-" + notifyData.substr(52, 2) + "-" + notifyData.substr(50, 2) + " " + notifyData.substr(48, 2) + ":" + notifyData.substr(46, 2) + ":" + notifyData.substr(44, 2),
                                d5: notifyData.substr(70, 2) + notifyData.substr(68, 2) + "-" + notifyData.substr(66, 2) + "-" + notifyData.substr(64, 2) + " " + notifyData.substr(62, 2) + ":" + notifyData.substr(60, 2) + ":" + notifyData.substr(58, 2),
                                d6: notifyData.substr(72, 2),
                                d7: parseInt(notifyData.substr(74, 2), 16),
                                d8: parseInt(`${notifyData.substr(82, 2)}${notifyData.substr(80, 2)}${notifyData.substr(78, 2)}${notifyData.substr(76, 2)}`, 16),
                                d9: parseInt(notifyData.substr(84, 2), 16),
                                d10: parseInt(`${notifyData.substr(88, 2)}${notifyData.substr(86, 2)}`, 16),
                                d11: util.hexToAscii(`${notifyData.substr(90, 2)}${notifyData.substr(92, 2)}${notifyData.substr(94, 2)}${notifyData.substr(96, 2)}${notifyData.substr(98, 2)}${notifyData.substr(100, 2)}${notifyData.substr(102, 2)}${notifyData.substr(104, 2)}`),
                                d12: util.hexToSignedInt(`${notifyData.substr(108, 2)}${notifyData.substr(106, 2)}`),
                                d13: util.hexToSignedInt(`${notifyData.substr(112, 2)}${notifyData.substr(110, 2)}`),
                                d14: util.hexToSignedInt(`${notifyData.substr(116, 2)}${notifyData.substr(114, 2)}`),
                                d15: parseInt(`${notifyData.substr(120, 2)}${notifyData.substr(118, 2)}`, 16),
                                d16: parseInt(`${notifyData.substr(124, 2)}${notifyData.substr(122, 2)}`, 16),
                                d17: parseInt(`${notifyData.substr(126, 2)}`, 16),
                                d18: parseInt(`${notifyData.substr(130, 2)}${notifyData.substr(128, 2)}`, 16),
                            }
                        })
                    }


                    if (that.data.type === '读参数'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        let portsArr = []
                        for (let i = 0; i < 8; i++) {
                            let portsData = {}
                            portsData[`d${13}`] = parseInt(`${notifyData.substr(162 + 2 + i * 38, 2)}`, 16);
                            portsData[`d${14}`] = parseInt(`${notifyData.substr(166 + 2 + i * 38, 2)}${notifyData.substr(164 + 2 + i * 38, 2)}`, 16);
                            portsData[`d${15}`] = parseInt(`${notifyData.substr(170 + 2 + i * 38, 2)}${notifyData.substr(168 + 2 + i * 38, 2)}`, 16);
                            portsData[`d${16}`] = notifyData.substr(172 + 2 + i * 38, 2);
                            portsData[`d${17}`] = notifyData.substr(174 + 2 + i * 38, 2);
                            portsData[`d${18}`] = `${notifyData.substr(182 + 2 + i * 38, 2)}${notifyData.substr(180 + 2 + i * 38, 2)}${notifyData.substr(178 + 2 + i * 38, 2)}${notifyData.substr(176 + 2 + i * 38, 2)}`;
                            portsData[`d${19}`] = parseInt(`${notifyData.substr(190 + 2 + i * 38, 2)}${notifyData.substr(188 + 2 + i * 38, 2)}${notifyData.substr(186 + 2 + i * 38, 2)}${notifyData.substr(184 + 2 + i * 38, 2)}`, 16);
                            portsData[`d${20}`] = parseInt(`${notifyData.substr(198 + 2 + i * 38, 2)}${notifyData.substr(196 + 2 + i * 38, 2)}${notifyData.substr(194 + 2 + i * 38, 2)}${notifyData.substr(192 + 2 + i * 38, 2)}`, 16);
                            portsArr.push(portsData)
                        }
                        that.setData({
                            portsArr: portsArr,
                            EAdata: {
                                d1: `${notifyData.substr(22, 2)}${notifyData.substr(20, 2)}${notifyData.substr(18, 2)}${notifyData.substr(16, 2)}`,
                                d2: util.hexToAscii(notifyData.substr(24, 2) + notifyData.substr(26, 2) + notifyData.substr(28, 2) + notifyData.substr(30, 2) + notifyData.substr(32, 2) + notifyData.substr(34, 2) + notifyData.substr(36, 2) + notifyData.substr(38, 2) + notifyData.substr(40, 2) + notifyData.substr(42, 2) + notifyData.substr(44, 2) + notifyData.substr(46, 2) + notifyData.substr(48, 2) + notifyData.substr(50, 2) + notifyData.substr(52, 2)),
                                d3: util.hexToAscii(notifyData.substr(54, 2) + notifyData.substr(56, 2) + notifyData.substr(58, 2) + notifyData.substr(60, 2) + notifyData.substr(62, 2) + notifyData.substr(64, 2) + notifyData.substr(66, 2) + notifyData.substr(68, 2) + notifyData.substr(70, 2) + notifyData.substr(72, 2) + notifyData.substr(74, 2) + notifyData.substr(76, 2) + notifyData.substr(78, 2) + notifyData.substr(80, 2) + notifyData.substr(82, 2)),
                                d4: util.hexToAscii(Array(20).fill(0).reduce((prev, cur, index, arr) => {
                                    return prev + notifyData.substr(84 + index * 2, 2);
                                }, '')),
                                d5: parseInt(notifyData.substr(130, 2), 16) + ":" + parseInt(notifyData.substr(128, 2), 16) + ":" + parseInt(notifyData.substr(126, 2), 16) + ":" + parseInt(notifyData.substr(124, 2), 16),
                                d6: parseInt(`${notifyData.substr(134, 2)}${notifyData.substr(132, 2)}`, 16),
                                d7: parseInt(notifyData.substr(142, 2), 16) + ":" + parseInt(notifyData.substr(140, 2), 16) + ":" + parseInt(notifyData.substr(138, 2), 16) + ":" + parseInt(notifyData.substr(136, 2), 16),
                                d8: parseInt(`${notifyData.substr(146, 2)}${notifyData.substr(144, 2)}`, 16),
                                d9: notifyData.substr(152, 2) + ":" + notifyData.substr(150, 2) + ":" + notifyData.substr(148, 2),
                                d10: parseInt(`${notifyData.substr(154, 2)}`, 16),
                                d11: parseInt(`${notifyData.substr(158, 2)}${notifyData.substr(156, 2)}`, 16),
                                d12: parseInt(`${notifyData.substr(160, 2)}`, 16),

                            }
                        }, function () {
                            console.log(that.data.EAdata)
                        })
                    }

                    if (that.data.type === '读表数据'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        console.log('notifyData.length', notifyData.length)
                        if (EBOriginData.length !== 610) {
                            EBOriginData = EBOriginData + notifyData
                        }
                        if (EBOriginData.length === 610) {
                            notifyData = EBOriginData
                            console.log(notifyData)
                            let portsArr = []
                            for (let i = 0; i < 8; i++) {
                                let portsData = {}
                                portsData[`d${14}`] = parseInt(`${notifyData.substr(74 + 4 + i * 66, 2)}`, 16);
                                portsData[`d${15}`] = `${notifyData.substr(82 + 4 + i * 66, 2)}${notifyData.substr(80 + 4 + i * 66, 2)}${notifyData.substr(78 + 4 + i * 66, 2)}${notifyData.substr(76 + 4 + i * 66, 2)}`;
                                portsData[`d${16}`] = `${notifyData.substr(90 + 4 + i * 66, 2)}${notifyData.substr(88 + 4 + i * 66, 2)}${notifyData.substr(86 + 4 + i * 66, 2)}${notifyData.substr(84 + 4 + i * 66, 2)}`;
                                portsData[`d${17}`] = `${notifyData.substr(98 + 4 + i * 66, 2)}${notifyData.substr(96 + 4 + i * 66, 2)}${notifyData.substr(94 + 4 + i * 66, 2)}${notifyData.substr(92 + 4 + i * 66, 2)}`;
                                portsData[`d${18}`] = `${notifyData.substr(106 + 4 + i * 66, 2)}${notifyData.substr(104 + 4 + i * 66, 2)}${notifyData.substr(102 + 4 + i * 66, 2)}${notifyData.substr(100 + 4 + i * 66, 2)}`;
                                portsData[`d${19}`] = `${notifyData.substr(114 + 4 + i * 66, 2)}${notifyData.substr(112 + 4 + i * 66, 2)}${notifyData.substr(110 + 4 + i * 66, 2)}${notifyData.substr(108 + 4 + i * 66, 2)}`;
                                portsData[`d${20}`] = parseInt(`${notifyData.substr(118 + 4 + i * 66, 2)}${notifyData.substr(116 + 4 + i * 66, 2)}`, 16);
                                portsData[`d${21}`] = parseInt(`${notifyData.substr(126 + 4 + i * 66, 2)}${notifyData.substr(124 + 4 + i * 66, 2)}${notifyData.substr(122 + 4 + i * 66, 2)}${notifyData.substr(120 + 4 + i * 66, 2)}`, 16);
                                portsData[`d${22}`] = util.hex2int(`${notifyData.substr(134 + 4 + i * 66, 2)}${notifyData.substr(132 + 4 + i * 66, 2)}${notifyData.substr(130 + 4 + i * 66, 2)}${notifyData.substr(128 + 4 + i * 66, 2)}`);
                                // portsData[`d${22}`]=parseInt(`${notifyData.substr(134+4+i*66,2)}${notifyData.substr(132+4+i*66,2)}${notifyData.substr(130+4+i*66,2)}${notifyData.substr(128+4+i*66,2)}`, 16);
                                portsData[`d${23}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0');
                                portsData[`d${231}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(6,8);
                                portsData[`d${232}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(5,6);
                                portsData[`d${233}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(4,5);
                                portsData[`d${234}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(3,4);
                                portsData[`d${235}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(2,3);
                                portsData[`d${236}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(1,2);
                                portsData[`d${237}`] = parseInt(`${notifyData.substr(136 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(0,1);
                                portsData[`d${24}`] = parseInt(`${notifyData.substr(138 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0');
                                portsData[`d${241}`] = parseInt(`${notifyData.substr(138 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(7,8);
                                portsData[`d${242}`] = parseInt(`${notifyData.substr(138 + 4 + i * 66, 2)}`, 16).toString(2).padStart(8, '0').substring(6,7);

                                console.log('portsData', portsData)
                                portsArr.push(portsData)
                            }
                            that.setData({
                                portsArr: portsArr,
                                EBdata: {
                                    d1: parseInt(`${notifyData.substr(16, 2)}`, 16),
                                    d2: notifyData.substr(30, 2) + notifyData.substr(28, 2) + "-" + notifyData.substr(26, 2) + "-" + notifyData.substr(24, 2) + " " + notifyData.substr(22, 2) + ":" + notifyData.substr(20, 2) + ":" + notifyData.substr(18, 2),
                                    d3: parseInt(`${notifyData.substr(32, 2)}`, 16),
                                    d4: parseInt(`${notifyData.substr(34, 2)}`, 16),
                                    d5: parseInt(`${notifyData.substr(36, 2)}`, 16),
                                    d6: util.hexToSignedInt(`${notifyData.substr(40, 2)}${notifyData.substr(38, 2)}`),
                                    d7: util.hexToSignedInt(`${notifyData.substr(40 + 4, 2)}${notifyData.substr(38 + 4, 2)}`),
                                    d8: util.hexToSignedInt(`${notifyData.substr(44 + 4, 2)}${notifyData.substr(42 + 4, 2)}`),
                                    d9: (`${notifyData.substr(52 + 4, 2)}${notifyData.substr(46 + 4, 2)}${notifyData.substr(48 + 4, 2)}${notifyData.substr(50 + 4, 2)}`),
                                    d10: parseInt(`${notifyData.substr(56 + 4, 2)}${notifyData.substr(54 + 4, 2)}`),
                                    d11: parseInt(`${notifyData.substr(60 + 4, 2)}${notifyData.substr(58 + 4, 2)}`, 16),
                                    d12: parseInt(`${notifyData.substr(64 + 4, 2)}${notifyData.substr(62 + 4, 2)}`, 16),
                                    d13: parseInt(`${notifyData.substr(72 + 4, 2)}${notifyData.substr(70 + 4, 2)}${notifyData.substr(68 + 4, 2)}${notifyData.substr(66 + 4, 2)}`, 16),

                                }
                            })
                        }

                    }
                    if (that.data.type === '读自测结果'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        that.setData({
                            EFdata: {
                                d1: parseInt(`${notifyData.substr(18, 2)}${notifyData.substr(16, 2)}`, 16),
                                d2: parseInt(`${notifyData.substr(22, 2)}${notifyData.substr(20, 2)}`, 16),
                                d3: parseInt(`${notifyData.substr(26, 2)}${notifyData.substr(24, 2)}`, 16),
                                d4: parseInt(`${notifyData.substr(30, 2)}${notifyData.substr(28, 2)}`, 16),
                                d5: parseInt(`${notifyData.substr(34, 2)}${notifyData.substr(32, 2)}`, 16),
                                d6: parseInt(`${notifyData.substr(36, 2)}`, 16),

                                d7: parseInt(`${notifyData.substr(38, 2)}`, 16),
                                d8: parseInt(`${notifyData.substr(40, 2)}`, 16),
                                d9: parseInt(`${notifyData.substr(42, 2)}`, 16),
                                d10: parseInt(`${notifyData.substr(44, 2)}`, 16),
                                d11: parseInt(`${notifyData.substr(46, 2)}`, 16),
                                d12: parseInt(`${notifyData.substr(48, 2)}`, 16),
                                d13: parseInt(`${notifyData.substr(50, 2)}`, 16),
                                d14: parseInt(`${notifyData.substr(52, 2)}`, 16),

                                d15: util.hex2int(`${notifyData.substr(60, 2)}${notifyData.substr(58, 2)}${notifyData.substr(56, 2)}${notifyData.substr(54, 2)}`),
                                d16: util.hex2int(`${notifyData.substr(68, 2)}${notifyData.substr(66, 2)}${notifyData.substr(64, 2)}${notifyData.substr(62, 2)}`),
                                d17: util.hex2int(`${notifyData.substr(76, 2)}${notifyData.substr(74, 2)}${notifyData.substr(72, 2)}${notifyData.substr(70, 2)}`),
                                d18: util.hex2int(`${notifyData.substr(84, 2)}${notifyData.substr(82, 2)}${notifyData.substr(80, 2)}${notifyData.substr(78, 2)}`),
                                d19: util.hex2int(`${notifyData.substr(92, 2)}${notifyData.substr(90, 2)}${notifyData.substr(88, 2)}${notifyData.substr(86, 2)}`),
                                d20: util.hex2int(`${notifyData.substr(100, 2)}${notifyData.substr(98, 2)}${notifyData.substr(96, 2)}${notifyData.substr(94, 2)}`),
                                d21: util.hex2int(`${notifyData.substr(108, 2)}${notifyData.substr(106, 2)}${notifyData.substr(104, 2)}${notifyData.substr(102, 2)}`),
                                d22: util.hex2int(`${notifyData.substr(116, 2)}${notifyData.substr(114, 2)}${notifyData.substr(112, 2)}${notifyData.substr(110, 2)}`),

                                d23: util.hex2int(`${notifyData.substr(60 + 64, 2)}${notifyData.substr(58 + 64, 2)}${notifyData.substr(56 + 64, 2)}${notifyData.substr(54 + 64, 2)}`),
                                d24: util.hex2int(`${notifyData.substr(68 + 64, 2)}${notifyData.substr(66 + 64, 2)}${notifyData.substr(64 + 64, 2)}${notifyData.substr(62 + 64, 2)}`),
                                d25: util.hex2int(`${notifyData.substr(76 + 64, 2)}${notifyData.substr(74 + 64, 2)}${notifyData.substr(72 + 64, 2)}${notifyData.substr(70 + 64, 2)}`),
                                d26: util.hex2int(`${notifyData.substr(84 + 64, 2)}${notifyData.substr(82 + 64, 2)}${notifyData.substr(80 + 64, 2)}${notifyData.substr(78 + 64, 2)}`),
                                d27: util.hex2int(`${notifyData.substr(92 + 64, 2)}${notifyData.substr(90 + 64, 2)}${notifyData.substr(88 + 64, 2)}${notifyData.substr(86 + 64, 2)}`),
                                d28: util.hex2int(`${notifyData.substr(100 + 64, 2)}${notifyData.substr(98 + 64, 2)}${notifyData.substr(96 + 64, 2)}${notifyData.substr(94 + 64, 2)}`),
                                d29: util.hex2int(`${notifyData.substr(108 + 64, 2)}${notifyData.substr(106 + 64, 2)}${notifyData.substr(104 + 64, 2)}${notifyData.substr(102 + 64, 2)}`),
                                d30: util.hex2int(`${notifyData.substr(116 + 64, 2)}${notifyData.substr(114 + 64, 2)}${notifyData.substr(112 + 64, 2)}${notifyData.substr(110 + 64, 2)}`),


                            }
                        })

                    }

                    if (that.data.type === '读事件记录'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        let type = notifyData.substr(18, 2)
                        if (type === '01') {
                            console.log('充值记录')
                            that.setData({
                                F0data: {}
                            })
                        }

                    }

                    if (that.data.type === '固件升级'&&notifyData.substr(14, 2).toUpperCase() !== 'E0') {
                        if (notifyData.substr(14, 2).toUpperCase() === 'EB') {
                            that.setData({
                                EBdata: {
                                    d3: parseInt(`${notifyData.substr(32, 2)}`, 16),
                                    d4: parseInt(`${notifyData.substr(34, 2)}`, 16),
                                }
                            },function (){
                                wx.request({
                                    url: `${config.prefix}/ota/latest_concentrator_firmwares`,

                                    method: 'GET',
                                    data: {
                                        from: `V${that.data.EBdata.d3}.${that.data.EBdata.d4}`,
                                        per_package_size: per_package_size
                                    },

                                    success: function (res) {
                                        console.log('get res', res)
                                        if (res.statusCode === 200) {
                                            that.setData({
                                                latest_concentrator_firmwares: res.data.data
                                            })
                                        } else {
                                            console.log('获取最新集中器固件失败')
                                            that.setData({
                                                latest_concentrator_firmwares: {}
                                            })
                                        }
                                    }
                                })
                            })
                        }
                        if (notifyData.substr(14, 2) === '89'&&Number(that.data.update_type)===1) {
                            //收到685e6857897600 89 0100 a616 0100需要发送的序号0001
                            console.log('--------------------------------------------------------------')
                            console.log('采集器向系统请求升级包（由采集器发起）')
                            let index = parseInt(`${notifyData.substr(18, 2)}${notifyData.substr(16, 2)}`, 16)
                            console.log('index', index)
                            // console.log('upgradeIndex',upgradeIndex)

                            that.handleSend89(index, (util.splitStringByLength(that.data.latest_concentrator_firmwares.content,per_package_size*2)[index-1].length)/2, util.splitStringByLength(that.data.latest_concentrator_firmwares.content,per_package_size*2)[index-1])

                            // wx.request({
                            //     url: `${config.prefix}/ota/concentrator_firmware_contents`,
                            //     method: 'GET',
                            //     data: {
                            //         from: that.data.selectFirmware.version,
                            //         index: index,
                            //         per_package_size: per_package_size
                            //     },
                            //     success: function (res) {
                            //         // console.log('get res', res)
                            //         if (res.statusCode === 200) {
                            //             // upgradeIndex++
                            //             console.log(`系统获取index: ${index} 内容成功 `)
                            //             // console.log(res.data.data)
                            //             let index2 = res.data.data.index;
                            //             let current_package_size = res.data.data.current_package_size;
                            //             let content = res.data.data.content;
                            //             that.handleSend89(index2, current_package_size, content)
                            //         } else {
                            //             console.log(`获取index: ${index} 内容失败 `)
                            //         }
                            //     }
                            // })

                        }
                        if (notifyData.substr(14, 2) === '89'&&Number(that.data.update_type)===2) {
                            //收到685e6857897600 89 0100 a616 0100需要发送的序号0001

                            console.log('--------------------------------------------------------------')
                            console.log('采集器向系统请求升级包（由采集器发起）')
                            let index = parseInt(`${notifyData.substr(18, 2)}${notifyData.substr(16, 2)}`, 16)
                            console.log('index', index)
                            // console.log('upgradeIndex',upgradeIndex)
                            const file_content=that.data.selectLocalFirmware.file_content;
                            that.handleSend89(index, (util.splitStringByLength(file_content,per_package_size*2)[index-1].length)/2, util.splitStringByLength(file_content,per_package_size*2)[index-1])

                        }


                    }

                });
            },
            fail: function (res) {
                console.log(res);
                that.writeLogs("接收数据失败: " + res.errCode, 'red');
                util.bleErrCode(res.errCode);
            }
        })
    },

    writeLogs(text, color) {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        let logs = this.data.logs;
        logs.unshift({
            color: color ? color : '#000',
            text: text,
            time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
        })
        this.setData({
            logs
        })
    },
    chooseLocalFirmware() {
        const that=this;
        wx.chooseMessageFile({
            type: 'file',
            count: 1,
            // extension: ['.bin'],
            success: function (res) {
                console.log(res)
                // console.log(res.tempFiles[0].path)
                // that.setData({
                //   fileList:res.fileList
                // })

                wx.getFileSystemManager()
                    .readFile({
                        filePath: res.tempFiles[0].path, // 文件路径
                        encoding: 'hex', // 返回格式
                        success: (res2) => {
                            // console.log(res2.data) //返回content:13740长度，然后自己截取
                            that.setData({
                                selectLocalFirmware:{
                                    file_name:res.tempFiles[0].name,
                                    file_size:res.tempFiles[0].size,
                                    file_content:res2.data,
                                    check_code:util.calc(util.addSpaceEveryTwoChars(res2.data)),
                                    per_package_size:per_package_size,
                                    package_count:Math.ceil(res.tempFiles[0].size/per_package_size),

                                }
                            },function(){
                                console.log(that.data.selectLocalFirmware)
                            })
                        },
                        fail(res) {
                            console.log('读取文件失败', res);
                            util.toastError('读取文件失败');
                        }
                    });
            }
        })
    },
    createBLEConnection() {
        console.log('createBLEConnection')
        this.setData({
            loading: true,
        })
        wx.createBLEConnection({
            deviceId: this.data.deviceId,
            success: (res) => {
                util.toastError('连接成功');
                this.writeLogs('连接成功')
                wx.setBLEMTU({
                    deviceId: this.data.deviceId,
                    mtu: 256,
                    success: (res) => {
                        console.log('设置MTU256成功')
                        this.writeLogs('设置MTU256成功')
                    },
                    fail: (res) => {
                        console.log('设置MTU失败')
                        console.log(res)
                    },
                })
                console.log("createBLEConnection success")
                this.setData({
                    connected: true,
                    loading: false,
                })

            },
            fail: (res) => {
                util.bleErrCode(res.errCode);
                this.writeLogs('连接失败,' + util.bleErrCode(res.errCode))
                console.log('连接失败')
                console.log(res)
                if (res.errCode === -1) {
                    this.setData({
                        connected: true,
                        loading: false,
                    })
                } else {
                    this.setData({
                        loading: false,
                    })
                }

            }
        })

    },
    closeBLEConnection() {
        const that = this
        wx.closeBLEConnection({
            deviceId: this.data.deviceId,
            success: (res) => {
                console.log("closeBLEConnection success")
                util.toastError('断开连接成功');
                that.writeLogs('断开连接成功')
                that.setData({
                    connected: false
                })

            },
            fail: (res) => {
                that.writeLogs('断开连接失败')
                console.log('断开连接失败')
                util.bleErrCode(res.errCode);
                console.log(res)
            }
        })


    },
    clickTop(e) {
        const ds = e.currentTarget.dataset
        const item = ds.item
        this.setData({
            active: item
        })
    },
    getBLEDeviceServices(deviceId) {
        const that = this
        wx.getBLEDeviceServices({
            deviceId: this.data.deviceId,
            success: (res) => {
                console.log('所有服务', res.services)
                let serviceIds = [];
                for (let i = 0; i < res.services.length; i++) {

                    //安卓上，部分机型获取设备服务时会多出 00001800 和 00001801 UUID 的服务，这是系统行为，注意不要使用这两个服务。
                    if (res.services[i].uuid.indexOf('00001800') >= 0 || res.services[i].uuid.indexOf('00001801') >= 0) {
                        console.log(`res.services[i].uuid ${res.services[i].uuid} 是系统行为，不要使用`)
                    } else {
                        console.log('res.services[i].uuid', res.services[i].uuid)
                        serviceIds.push(res.services[i].uuid)

                    }

                }
                this.setData({
                    serviceIds: serviceIds
                }, function () {
                    for (let i = 0; i < this.data.serviceIds.length; i++) {
                        setTimeout(function () {
                            that.getBLEDeviceCharacteristics(deviceId, that.data.serviceIds[i])
                        }, 100)

                    }
                })
            }
        })
    },
    getBLEDeviceCharacteristics(deviceId, serviceId) {

        wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: (res) => {
                console.log('getBLEDeviceCharacteristics success', res.characteristics)
                let findWrite = find(res.characteristics, function (o) {
                    return o.properties.write
                })
                let findNotify = find(res.characteristics, function (o) {
                    return o.properties.notify
                })


                if (findWrite && findNotify) {

                    this.setData({
                        selectServerChars: {
                            deviceId: deviceId,
                            serviceId: serviceId,
                            writeCharUUID: findWrite.uuid,
                            notifyCharUUID: findNotify.uuid,
                        }
                    }, function () {
                        this.recvBLECharacterNotice(deviceId, serviceId, this.data.selectServerChars.notifyCharUUID);
                        this.writeLogs(`发现服务${JSON.stringify(this.data.selectServerChars)}`, 'rgb(232,137,60)')
                        this.handleSendE0()

                    })

                }


            },
            fail(res) {
                console.log('serviceId 出错了', serviceId)
                console.error('getBLEDeviceCharacteristics', res)
                util.bleErrCode(res.errCode);
                that.writeLogs(util.bleErrCode(res.errCode), 'red')
            }
        })
        //监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
        wx.onBLECharacteristicValueChange((characteristic) => {
            console.log(characteristic.value)

        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log('onHIde')
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('onUnload')
        // this.closeBLEConnection()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    // onPullDownRefresh() {
    //
    // },

    /**
     * 页面上拉触底事件的处理函数
     */
    // onReachBottom() {
    //
    // },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage() {

    // }
})
